# -*- coding: utf-8 -*-

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
import json
from common.helper import Helper
from threading import Thread


class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "i保终身重大疾病保险2019版"

    # 生成产品数据
    def genProductInfo(self):

        plan = {

            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 18)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "500000"],
                # 保障期间 0 趸交 60A 到60岁
                "interval": ["0", "3", "5", "10", "15", "20", "25", "30", "60A"],
                # 缴费方式
                "payType": ["年缴", "月缴"],
                # 保障期限
                "expire": ["终身"],
                # 附加意外保险 默认不投保
                "ext_item": ["0"],
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(18, 36)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000"],
                # 保障期间 0 趸交 60A 到60岁
                "interval": ["0", "3", "5", "10", "15", "20", "25", "30", "60A"],
                # 缴费方式
                "payType": ["年缴", "月缴"],
                # 保障期限
                "expire": ["终身"],
                # 附加意外保险 默认不投保
                "ext_item": ["0"],
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(36, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000"],
                # 保障期间 0 趸交 60A 到60岁
                "interval": ["0", "3", "5", "10", "15", "20", "25", "60A"],
                # 缴费方式
                "payType": ["年缴", "月缴"],
                # 保障期限
                "expire": ["终身"],
                # 附加意外保险 默认不投保
                "ext_item": ["0"],
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000"],
                # 保障期间 0 趸交 60A 到60岁
                "interval": ["0", "3", "5", "10", "15", "20", "60A"],
                # 缴费方式
                "payType": ["年缴", "月缴"],
                # 保障期限
                "expire": ["终身"],
                # 附加意外保险 默认不投保
                "ext_item": ["0"],
            },
            "planE": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000"],
                # 保障期间 0 趸交 60A 到60岁
                "interval": ["0", "3", "5", "10", "15", "60A"],
                # 缴费方式
                "payType": ["年缴", "月缴"],
                # 保障期限
                "expire": ["终身"],
                # 附加意外保险 默认不投保
                "ext_item": ["0"],
            },

        }
        for k in plan:

            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["interval"],
                             plan[k]["payType"], plan[k]["expire"], plan[k]["ext_item"]):

                if v[3] == "0" :

                    payType = "一次缴清"

                    data = {

                        "year":v[0],
                        "gender":v[1],
                        "money":v[2],
                        "interval":v[3],
                        "payType":payType

                    }
                    result = self.filterRey( data )

                    if not result:

                        # 写入数据库
                        self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                            v[0], v[1], v[2], v[3],payType, v[5], v[6]
                        ))
                        self.mysql._conn.commit()
                        print(
                            domain[self.name]["insert_sql"].format(

                                v[0], v[1], v[2],v[3],payType, v[5], v[6]
                            )
                        )

                else:
                    # 写入数据库
                    self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                    ))
                    self.mysql._conn.commit()
                    print(
                        domain[self.name]["insert_sql"].format(

                            v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                        )
                    )

    # 过滤信息
    def filterRey(self,data):

        SQL = 'SELECT * FROM `i保终身重大疾病保险2019版` WHERE `year` = "{year}" AND `gender` = "{gender}" AND `money` = "{money}" AND `interval`="{interval}" AND  `payType` = "{payType}"'

        self.mysql.cursor.execute( SQL.format( ** data ))

        result = self.mysql.cursor.fetchone()

        if result:

            return True

        else:

            return False


    # 执行爬虫
    def requestJson(self, dt=None,mysql=None):

        if dt["payType"] == "年缴" or dt["payType"] == "一次缴清":

            payWay = "Y"

        else:

            payWay = "M"

        if dt["interval"] == "60A":

            interval = "A60"

        elif dt["interval"] == "0":

            interval = "Y1"

        else:

            interval = "Y" + dt["interval"]

        data = {"age": (dt["year"]), "amount": dt["money"], "itemCode": "WDDO", "payMent": interval, "payWay": payWay, "period": "A106",
                "productCode": "WDDO", "sex": "1" if dt["gender"] == "M" else "0", "attachRisks": []}

        payload = json.dumps( data )

        r = requests.post( url = domain[self.name]["url"],headers = domain[self.name]["header"],data=payload)
        print( r.json())
        if r.status_code == 200 and r.json()["code"] == 200:

            price = Helper.decimalParse(r.json()["data"]["premiumCalResultMap"]["WDDO"]["premium"])

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            mysql.updatePrice( data )

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*更新产品价格失败:%d*/" % dt["id"])

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):
        for i in range(3):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))
            # p = Thread( target=self.test,args=(mysql,))

            t.start()


